<template>
  <div class="history-page">
    <el-card class="history-card">
      <template #header>
        <div class="card-header">
          <h2>生成历史</h2>
          <p class="subtitle">查看您的表情包生成记录</p>
        </div>
      </template>

      <el-table 
        v-loading="loading"
        :data="records"
        style="width: 100%"
      >
        <el-table-column label="预览" width="120">
          <template #default="scope">
            <el-image 
              :src="scope.row.original_url || scope.row.output_url"
              :preview-src-list="[scope.row.original_url || scope.row.output_url]"
              fit="cover"
              style="width: 50px; height: 50px"
            />
          </template>
        </el-table-column>

        <el-table-column prop="text" label="文本描述" />
        <el-table-column prop="style" label="风格" width="100" />
        <el-table-column prop="created_at" label="创建时间" width="180" />

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button-group>
              <el-button 
                type="primary" 
                size="small"
                @click="downloadImage(scope.row)"
              >
                <el-icon><Download /></el-icon>
              </el-button>
              <el-button 
                type="info" 
                size="small"
                @click="copyLink(scope.row)"
              >
                <el-icon><Link /></el-icon>
              </el-button>
              <el-button 
                type="danger" 
                size="small"
                @click="deleteRecord(scope.row)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download, Link, Delete } from '@element-plus/icons-vue'
import axios from 'axios'

const API_BASE_URL = 'http://localhost:5000'
const loading = ref(false)
const records = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 获取历史记录
const fetchHistory = async () => {
  loading.value = true
  try {
    const token = localStorage.getItem('token')
    const response = await axios.get(
      `${API_BASE_URL}/api/history`, {
        params: {
          page: currentPage.value,
          per_page: pageSize.value
        },
        headers: {
          'Authorization': `Bearer ${token}`
        }
      }
    )
    
    if (response.data.status === 'success') {
      records.value = response.data.data.records
      total.value = response.data.data.total
    }
  } catch (error) {
    ElMessage.error('获取历史记录失败')
  } finally {
    loading.value = false
  }
}

// 下载图片
const downloadImage = async (record) => {
  try {
    const response = await axios.get(record.original_url || record.output_url, {
      responseType: 'blob'
    })
    const url = window.URL.createObjectURL(response.data)
    const link = document.createElement('a')
    link.href = url
    link.download = `emoji_${record.id}.png`
    link.click()
    window.URL.revokeObjectURL(url)
    ElMessage.success('下载成功')
  } catch (error) {
    ElMessage.error('下载失败')
  }
}

// 复制链接
const copyLink = (record) => {
  const url = record.original_url || record.output_url
  navigator.clipboard.writeText(url)
    .then(() => ElMessage.success('链接已复制'))
    .catch(() => ElMessage.error('复制失败'))
}

// 删除记录
const deleteRecord = async (record) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条记录吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const token = localStorage.getItem('token')
    const response = await axios.delete(
      `${API_BASE_URL}/api/history`, {
        params: { id: record.id },
        headers: {
          'Authorization': `Bearer ${token}`
        }
      }
    )
    
    if (response.data.status === 'success') {
      ElMessage.success('删除成功')
      fetchHistory()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchHistory()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchHistory()
}

onMounted(() => {
  fetchHistory()
})
</script>

<style scoped>
.history-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.history-card {
  margin-bottom: 20px;
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0;
  color: var(--el-text-color-primary);
}

.subtitle {
  margin: 10px 0 0;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.el-table {
  margin-top: 20px;
}
</style> 